Categories
Vue

Using Firebase in a Vue App Vuefire — References and Querying

Spread the love

The Vuefire library lets us add Firebase database manipulation capabilities right from our Vue app.

In this article, we’ll look at how to use Vuefire to add support for Cloud Firestore database manipulation into our Vue app.

References to Other Documents

We can store references to other documents by referencing them.

This only works with the Cloud Firestore.

For example, we can write:

App.vue

<template>
  <div>
    <div v-for="c of cities" :key="c.id">{{c}}</div>
  </div>
</template>
<script>
import { db } from "./db";
const books = db.collection("books");
export default {
  data() {
    return {
      cities: []
    };
  },
  firestore: {
    cities: db.collection("cities")
  },
  async mounted() {
    await db.collection("cities").add({
      name: "London",
      books: [books.doc("1")]
    });
  }
};
</script>

db.js

import firebase from "firebase/app";
import "firebase/firestore";
export const db = firebase
  .initializeApp({ projectId: "project-id" })
  .firestore();
const { Timestamp, GeoPoint } = firebase.firestore;
export { Timestamp, GeoPoint };

We just reference the documents we want in an array to make a reference to them.

Then we can see the document wherever we reference it.

Unbinding or Unsubscribing to Changes

We can unbind any references to a collection by using the this.$unbind method.

We just have to pass in the collection name to the method:

this.$unbind('book')

Vuefire will reset the property by default.

So if we have:

this.$unbind('book')

or

this.$unbind('book', true)

then the this.book value will be reset to null .

If we have:

this.$unbind('book', false)

Then this.book will keep whatever value it has before.

We can also reset it to the value we want by passing in a function that returns the value we want to reset to:

this.$unbind('book', () => ({ title: 'foo' }))

If we reset a collection, then the value it’s bound to will be reset to an empty array.

So if we have:

this.$unbind('books')

then this.books will be [] after it’s been reset if books is bound to this.books .

We can also change the value when we call this.$bind :

await this.$bind('user', userRef)
this.$bind('user', otherUserRef, { reset: false })

They let us bind to the value we want.

Querying the Database

We can query the database with Vuefire.

For example, we can write:

<template>
  <div>
    <div v-for="b of books" :key="b.id">{{b}}</div>
  </div>
</template>
<script>
import { db } from "./db";
export default {
  data() {
    return {
      books: []
    };
  },
  mounted() {
    db.collection("books")
      .get()
      .then(querySnapshot => {
        const books = querySnapshot.docs.map(doc => doc.data());
        this.books = books;
      });
  }
};
</script>

We called the db.collection method to get the collection.

The get method gets the query results snapshot.

And then docs.map map the snapshot to data that we can use in our component.

In the template, we loop through the entries.

We can also query a single document by ID by using the doc method:

<template>
  <div>{{book}}</div>
</template>
<script>
import { db } from "./db";
export default {
  data() {
    return {
      book: {}
    };
  },
  mounted() {
    db.collection("books")
      .doc("UGRbRLiAzIl2efo1tmVP")
      .get()
      .then(snapshot => {
        const book = snapshot.data();
        this.book = book;
      });
  }
};
</script>

Where UGRbRLiAzIl2efo1tmVP is the ID of the document we’re looking for.

snapshot.data() returns the JavaScript object for the document.

Conclusion

We can save references to other documents in our app.

Also, we can unsubscribe to changes manually for a collection.

And there’re several ways to query a database with Vuefire.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *